package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Holder;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
@Slf4j

public class LoginInterceptor implements HandlerInterceptor {

    StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
////        TODO 1、获取请求头中的token
//
//        log.info("进入拦截器");
//        String token = request.getHeader("authorization");
//
//        log.info("token 是"+token);
//        System.out.println(token);
//
//        if(token==null){
//            response.setStatus(401);
//            return false;
//        }
//        String token1 = LOGIN_USER_KEY + token;
////        TODO 2、从TOKEN中获取用户对象
//        Map<Object, Object> UserMap = stringRedisTemplate.opsForHash().entries(token1);
//        if(UserMap.isEmpty()){
//            response.setStatus(401);
//            return false;
//        }
////        TODO 3、将对象转换为DTO对象，原本是Map类型
//        UserDTO userDTO = BeanUtil.fillBeanWithMap(UserMap, new UserDTO(), false);
////        TODO 4、将对象放入ThreadLocal中
//        UserHolder.saveUser(userDTO);
//        System.out.println(userDTO);
//        stringRedisTemplate.expire(token1,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
//        return true;


//        HttpSession session=request.getSession();
//        Object user = session.getAttribute("user");

//        if(user==null){
//
//            return false;
//        }
//        UserHolder.saveUser((UserDTO) user);
//        return true;

        UserDTO user = UserHolder.getUser();
//        log.info(user.toString());
        if (user==null){
            response.setStatus(401);
            return false;
        }
        return true;


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        UserHolder.removeUser();

        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);


    }
}
